import React, { useEffect,useState } from 'react'
import { deleteBannerFn, getBannerList, updateBannerStatusFn } from '../../api/banner'
import {Table,Image,Switch,Button,Popconfirm,message} from 'antd'
import { DeleteOutlined } from '@ant-design/icons'
import { useSelector } from 'react-redux'
export default function Index() {
  // 轮播图列表
  const [bannerList, setBannerList]= useState([])
  // 当前页码
  const [current, setCurrent]= useState(1)
  // 用户信息
  const userInfo=useSelector(state=>state.user.userInfo)
    // -----------删除轮播图-------------
  // 取消删除
  const deleteCancel = () => {
    message.warning('取消了删除')
  }

  // 轮播图删除
  const deleteBanner = (bannerid) => {
    message.warning('删除了' + bannerid)
    deleteBannerFn(bannerid).then(res => {
      console.log(res);
      if (res.code == 200) {
        message.success(res.message)
        // 获取轮播图列表,直接刷新页面，因为删除最后一位轮播图，会出现页面bug
        // window.location.reload()
        getMyBannerList()
      }
    })
  }
  // -----------删除轮播图-------------
  const columns = [
    {
      title: '序号',
      render(v,r,i) { 
        return <span>{(current-1)*8+i+1}</span>
      }
    },
    {
      title: '图片',
      dataIndex: 'img',
      key: 'bannerImg',
      render: (text) => <Image src={text} style={{width: '100px'}}></Image>
    },
    {
      title: '是否显示',
      dataIndex: 'flag',
      key: 'flag',
      render: (Checked,r) => <Switch checked={Checked} onChange={(mychecked)=>{
        updataBannerChecked(mychecked,r)
      }}></Switch>
    },
    {
      title: '操 作',
      render(r, t, index) {
        return <>
        {/* 气泡确认框 */}
          <Popconfirm
            title="温馨提示"
            // 可以套标签实现样式添加
            description={<span>你确定要删除<span style={{ color: 'red' }}>{t.bannerid}</span>吗</span>}
            onConfirm={() => {
              deleteBanner (t.bannerid)
            }}
            onCancel={() => { deleteCancel() }}
            okText="确定"
            cancelText="取消"
          >
            <Button disabled={userInfo?.role==1?true:false} style={{ marginLeft: "10px" }} icon={<DeleteOutlined />} danger>删除</Button>
          </Popconfirm>
        </>
      }
    }
    
  ]

  // 获取轮播图
  const getMyBannerList = () => { 
    getBannerList().then(res => { 
      setBannerList([...res.data])
     })
  }
  const updataBannerChecked=(checked,r) => { 
    // 修改数据更新轮播图状态
    updateBannerStatusFn({bannerid: r.bannerid, flag: checked}).then(res => { 
      console.log(res);
      getMyBannerList()
    })
  }
  useEffect(() => {
    // useEffect不允许async，因为只允许返回一个函数，不能是一个promise
    getMyBannerList()
  }, [])
  return (
    <div>
      <Table 
      // table滚动
      scroll={{y:450}}
      rowKey={'bannerid'}
      dataSource={bannerList}
      columns={columns} 
      pagination={{pageSize:8 ,onChange(page){
        setCurrent(page)}, responsive: true,current}} ></Table>

    </div>
  )
}
